/**
 * 
 */
package com.zho.common.velocity;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;

import com.zho.util.Logit;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class VelocityHelper {
    private static final Logit log = Logit.getInstance(VelocityHelper.class);

    /**
     * 
     */
    public static String execute(StringReader source) throws Exception {
        return execute(source, SpringVelocityTools.createContext(), null);
    }

    /**
     * 
     * @param source
     * @param params
     * @return
     * @throws Exception
     */
    public static String execute(StringReader source, Map<String, Object> params) throws Exception {
        return execute(source, SpringVelocityTools.createContext(), params);
    }

    /**
     * 
     * @param source
     * @param context
     * @return
     * @throws Exception
     */
    public static String execute(StringReader source, Context context) throws Exception {
        return execute(source, context, null);
    }

    /**
     * 
     * @param source
     * @param params
     * @return
     * @throws Exception
     */
    public static String execute(StringReader source, Context context, Map<String, Object> params) throws Exception {
        StringWriter out = new StringWriter();
        try {
            Velocity.evaluate(populate(context, params), out, "", source);
        } catch (ResourceNotFoundException rnfe) {
            throw new Exception("execute()", rnfe);
        } catch (ParseErrorException pee) {
            throw new Exception("execute()", pee);
        } catch (Exception e) {
            throw new Exception("execute()", e);
        }
        return out.toString();
    }

    /**
     * 
     * @param context
     * @param params
     * @return
     */
    private static Context populate(Context context, Map<String, Object> params) {
        context = (context == null ? SpringVelocityTools.createContext() : context);
        if (params != null) {
            Iterator<String> iter = params.keySet().iterator();
            String key;
            while (iter.hasNext()) {
                key = iter.next();
                context.put(key, params.get(key));
            }
        }
        return context;
    }
}
